package com.yvon.maple.service.auth.valicode.validate.code.generator;

import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import com.yvon.maple.service.auth.param.CodeParam;
import com.yvon.maple.service.auth.valicode.validate.code.image.ImageCodeVo;
import com.yvon.maple.service.auth.valicode.validate.code.properties.CodeProperties;
import com.yvon.maple.service.auth.valicode.validate.code.properties.ImageCodeProps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 图片验证码生成器
 * @author : Yvon
 * @since 2019/5/26
 */
@Slf4j
@Component(ImageCodeGenerator.GENERATOR)
public class ImageCodeGenerator implements CodeGenerator {

	public static final String GENERATOR = "imageCodeGenerator";

	/**
	 * 系统配置
	 */
	@Autowired
	private CodeProperties codeProperties;

	@Override
	public ImageCodeVo generate(CodeParam param) {
		Captcha captcha = createCaptcha();
		//输出code
		String image = captcha.toBase64("data:" + codeProperties.getImage().getType().getContentType() + ";base64,");
		return new ImageCodeVo(image, captcha.text(), codeProperties.getImage().getExpire(), param.getKey());
	}

	private Captcha createCaptcha() {
		Captcha captcha;
		ImageCodeProps.CaptchaType type= codeProperties.getImage().getType();
		int width = codeProperties.getImage().getWidth();
		int height = codeProperties.getImage().getHeight();
		int len = codeProperties.getImage().getLength();
		switch (type) {
			case GIF:
				captcha = new GifCaptcha(width, height, len);
				break;
			case SPEC:
				captcha = new SpecCaptcha(width, height, len);
				break;
			case CHINESE:
				captcha = new ChineseCaptcha(width, height, len);
				break;
			case CHINESE_GIF:
				captcha = new ChineseGifCaptcha(width, height, len);
				break;
			case ARITHMETIC:
			default:
				captcha = new ArithmeticCaptcha(width, height, len);
				break;
		}
		captcha.setCharType(codeProperties.getImage().getCharType());

		return captcha;
	}

}